﻿using System;
using System.Collections.Generic;
using NHibernate;
using SimpleScrum.Core.Entities;
using SimpleScrum.Helpers;

namespace SimpleScrum.Areas.Scrum.Models
{
    public class UserStoryTaskModel
    {
        private ISession _session;

        public IList<UserStoryTask> GetTasks(Guid userStoryId)
        {
            IList<UserStoryTask> tasks;
            using (_session = NHibernateHelper.GetSession())
            {
                //NHibernate query 
                IQuery query =
                    _session.CreateQuery("from UserStoryTask where UserStoryId='" + userStoryId + "';");
                tasks = query.List<UserStoryTask>();
            }
            return tasks;
        }

        public UserStoryTask GetTaskById(Guid id)
        {
            UserStoryTask userStoryTask;
            using (_session = NHibernateHelper.GetSession())
            {
                using (ITransaction tran = _session.BeginTransaction())
                {
                    userStoryTask = _session.Get<UserStoryTask>(id);
                    tran.Commit();
                }
            }
            return userStoryTask;
        }

        public bool NewTask(UserStoryTask userStoryTask)
        {
            using (_session = NHibernateHelper.GetSession())
            {
                using (ITransaction tran = _session.BeginTransaction())
                {
                    _session.Save(userStoryTask);
                    tran.Commit();
                }
            }
            return true;
        }

        public void UpdateTask(UserStoryTask userStoryTask)
        {
            using (_session = NHibernateHelper.GetSession())
            {
                using (ITransaction tran = _session.BeginTransaction())
                {
                    _session.Update(userStoryTask);
                    tran.Commit();
                }
            }
        }

        public void DeleteTask(UserStoryTask UserStoryTask)
        {
            using (_session = NHibernateHelper.GetSession())
            {
                using (ITransaction tran = _session.BeginTransaction())
                {
                    try
                    {
                        _session.Delete(UserStoryTask);
                        tran.Commit();
                    }
                    catch (Exception ex)
                    {
                        string msg = ex.Message;
                    }
                }
            }
        }
    }
}